package com.wuchao.utils;

import com.wuchao.entity.Bookstore;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import javax.sql.rowset.spi.XmlWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author wuchao66
 * @Date 2023/11/1 14:27
 * @PackageName:com.wuchao.utils
 * @ClassName: Txml
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
public class Txml {
    public static void main(String[] args) throws DocumentException, IOException {
        //简历读取器
        SAXReader reader = new SAXReader();
        //得到文档树
        Document dom = reader.read(new File("D:\\idea-project\\t169ssmbt\\src\\main\\resources\\books.xml"));
        //得到根节点
        Element gen = dom.getRootElement();
        //根下面加新的孩子
//        Element steam = gen.addElement("steam");
//        //新节点属性
//        steam.setAttributeValue("id","4");
//        Element xxx = steam.addElement("xxx");
//        xxx.setText("我是新的孙子");
        //steam.remove(xxx);
        //拿到根下面的子集合
        Iterator zis = gen.elementIterator();
        //循环遍历子集合
       List<Bookstore> list = new ArrayList<>();
        while(zis.hasNext()){
            Bookstore bookstore = new Bookstore();
            //得到每一个孩子
            Element zi = (Element)zis.next();
            //孩子的属性
            List<Attribute> attributes = zi.attributes();
            //输出孩子属性
            attributes.forEach(xjj-> {
                System.out.println("属性名" + xjj.getName() + "\t属性值" + xjj.getValue());
                    if(xjj.getName().equals("id")){
                        bookstore.id=Integer.parseInt(xjj.getValue())   ;
                    }

            } );

            //得到孩子的孩子集合
            Iterator suns = zi.elementIterator();
            //循环遍历孙节点
            while(suns.hasNext()){
                Element sun = (Element)suns.next();
                System.out.println("孙节点的名字"+sun.getName()+"\t"+"孙节点的值"+sun.getStringValue());
                if(sun.getName().equals("name")){
                    bookstore.name=sun.getStringValue();
                }
            }
            list.add(bookstore);
        }
        //输出成为一个新的xml 文件
//        XMLWriter writer = new XMLWriter(
//                new FileWriter("D:\\idea-project\\t169ssmbt\\src\\main\\resources\\newbooks.xml"));
//        writer.write(dom);
//        writer.close();
//        System.out.println("输出完毕");
        list.forEach(System.out::println);

    }
}
